package com.kuangjia.scenic_spot_ticket.controller;

import com.kuangjia.scenic_spot_ticket.common.Result;
import com.kuangjia.scenic_spot_ticket.entity.TicketOrder;
import com.kuangjia.scenic_spot_ticket.service.TicketOrderService;
import com.kuangjia.scenic_spot_ticket.dto.TicketOrderDTO;
import com.kuangjia.scenic_spot_ticket.entity.User;
import com.kuangjia.scenic_spot_ticket.entity.ScenicSpot;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kuangjia.scenic_spot_ticket.mapper.UserMapper;
import com.kuangjia.scenic_spot_ticket.mapper.ScenicSpotMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.stream.Collectors;
import java.math.BigDecimal;

@RestController
@RequestMapping("/api/orders")
public class TicketOrderController {
    @Autowired
    private TicketOrderService ticketOrderService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ScenicSpotMapper scenicSpotMapper;

    @GetMapping
    public Result<List<TicketOrder>> list() {
        return Result.success(ticketOrderService.list());
    }

    @PostMapping
    public Result<BigDecimal> add(@RequestBody TicketOrder order) {
        try {
            BigDecimal balance = ticketOrderService.buyTicket(order);
            return Result.success(balance);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @DeleteMapping("/{id}")
    public Result<Boolean> delete(@PathVariable Long id) {
        return Result.success(ticketOrderService.removeById(id));
    }

    @GetMapping("/page")
    public Result<Page<TicketOrderDTO>> page(@RequestParam(defaultValue = "1") int page,
                                          @RequestParam(defaultValue = "10") int size,
                                          @RequestParam(required = false) Long userId,
                                          @RequestParam(required = false) String keyword) {
        LambdaQueryWrapper<TicketOrder> wrapper = new LambdaQueryWrapper<>();
        if (userId != null) {
            wrapper.eq(TicketOrder::getUserId, userId);
        }
        if (keyword != null && !keyword.isEmpty()) {
            // 先查出所有匹配用户名的userId
            List<Long> userIds = userMapper.selectList(
                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<User>()
                    .like(User::getUsername, keyword)
            ).stream().map(User::getId).toList();
            // 查出所有匹配景点名的scenicSpotId
            List<Long> spotIds = scenicSpotMapper.selectList(
                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ScenicSpot>()
                    .like(ScenicSpot::getName, keyword)
            ).stream().map(ScenicSpot::getId).toList();
            wrapper.and(w ->
                w.like(TicketOrder::getId, keyword)
                 .or(userIds.size() > 0, x -> x.in(TicketOrder::getUserId, userIds))
                 .or(spotIds.size() > 0, x -> x.in(TicketOrder::getScenicSpotId, spotIds))
            );
        }
        Page<TicketOrder> orderPage = ticketOrderService.page(new Page<>(page, size), wrapper);
        // 转换为DTO，查用户名和景点名
        Page<TicketOrderDTO> dtoPage = new Page<>(orderPage.getCurrent(), orderPage.getSize(), orderPage.getTotal());
        List<TicketOrderDTO> dtoList = orderPage.getRecords().stream().map(order -> {
            TicketOrderDTO dto = new TicketOrderDTO();
            dto.setId(order.getId());
            dto.setQuantity(order.getQuantity());
            dto.setTotalPrice(order.getTotalPrice());
            dto.setOrderTime(order.getOrderTime());
            // 查用户名
            User user = userMapper.selectById(order.getUserId());
            dto.setUsername(user != null ? user.getUsername() : "");
            // 查景点名
            ScenicSpot spot = scenicSpotMapper.selectById(order.getScenicSpotId());
            dto.setScenicSpotName(spot != null ? spot.getName() : "");
            return dto;
        }).collect(Collectors.toList());
        // 强制限制返回条数不超过size
        if (dtoList.size() > size) {
            dtoList = dtoList.subList(0, size);
        }
        dtoPage.setRecords(dtoList);
        return Result.success(dtoPage);
    }
} 